import cv2
import numpy as np
import time

# 读入原始图像
img = cv2.imread("image.jpg")

# 设定旋转角度、旋转中心点和缩放比例
angle = 30
center = (img.shape[1]//2, img.shape[0]//2)
scale = 1

# 生成旋转矩阵
M = cv2.getRotationMatrix2D(center, angle, scale)

# 计算旋转后的图像并记录耗时
start_time = time.time()
rotated_img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
end_time = time.time()
time_cost = int((end_time - start_time) * 1000)
print("Rotation time cost: {}ms".format(time_cost))

# 显示旋转后的图像
cv2.imshow("Rotated Image", rotated_img)
cv2.imwrite('Rotated Image.jpg', rotated_img)
cv2.waitKey()

# 生成反向旋转矩阵
M_inv = cv2.invertAffineTransform(M)

# 计算反向旋转后的图像并记录耗时
start_time = time.time()
recovered_img = cv2.warpAffine(rotated_img, M_inv, (img.shape[1], img.shape[0]))
end_time = time.time()
time_cost = int((end_time - start_time) * 1000)
print("Recovery time cost: {}ms".format(time_cost))

# 显示反向旋转后的图像
cv2.imshow("Recovered Image", recovered_img)
cv2.imwrite('Recovered Image.jpg', recovered_img)
cv2.waitKey()

# 比对原始图像和反向旋转后的图像的灰度值差异
diff = cv2.absdiff(img, recovered_img)
if np.sum(diff) == 0:
    print("The difference of gray value between original and recovered image is 0.")
else:
    print("The difference of gray value between original and recovered image is {}.".format(np.sum(diff)))
